﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AspMvcWebClient.AwesomeServiceReference;
using AspMvcWebClient.ExampleDataCalls;
using AspMvcWebClient.Models;

namespace AspMvcWebClient.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            ViewBag.test = "Hejsan";

            return View("Login");
        }

        public ActionResult CheckLogin(string user, string pass)
        {
            var service = new AwesomeClient();
            var userObj = service.LoginPlayer(user, pass);

            if (userObj != null) // Jämför inmatade namnet med databasen
            {
                Session["User"] = userObj.PlayerName;
                Session["UserId"] = userObj.PlayerId;
                ViewBag.user = userObj.PlayerName;
                return GoToStart();

            } else {
                ViewBag.FailMessage = "Inloggningen misslyckades.";
                return View("Login");
            }

        }

        public ActionResult GameChosen(string gameSelect, string roundsSelect)
        {
            int numOfRounds;
            Int32.TryParse(roundsSelect, out numOfRounds);

            int gameId;
            Int32.TryParse(gameSelect, out gameId);

            int userId; 
            Int32.TryParse(Session["UserId"].ToString(), out userId);

            var service = new AwesomeClient();

            service.CreateNonrandomGamesession(userId, gameId, numOfRounds);

            return GoToStart();

            //Session["GameSessionId"] = 1; // Statisk data än så länge

            //ViewBag.GameSessionId = 0;
            //ViewBag.NumOfRounds = numOfRounds;
            //ViewBag.CurrentRound = 1;

            //Spara (skapa) spelsessionen i databasen, gameSelect = spelval och numOfRounds = antal omgångar

        }

        /// <summary>
        /// Hämtar speltitlar och spelsessioner som spelaren kan joina. Visar sidan för att starta ett spel.
        /// </summary>
        /// <returns></returns>
        public ActionResult NewGame() 
        {
            GetGameTitles();
            ViewBag.Games = ExampleData.Games();

            var service = new AwesomeClient();
            var model = service.GetAllActiveGameSessions();
            GetGameTitles();

            return View("NewGame", model);
        }        

        public void GetActiveGames(string user) //Hämta användarens spel ("spelsessioner")
        {
            //List<GameSession> gameSessions = ExampleData.GameSessions();

            //List<SpelSession> gameSessions = new List<SpelSession>(); //Används när det finns koppling till databsen
            //gameSessions = serviceClient.GetSpelSession(user);

            var service = new AwesomeClient();
            ViewBag.GameSessions = service.GetAllActiveGameSessions();
        }

        public void GetGameTitles() // Hämta alla speltitlar
        {
            var service = new AwesomeClient();
            ViewBag.GameTitles = service.GetGame();
        }

        public List<Player> GetPlayers() // Hämta alla tillgängliga spelare eller endast online?
        {
            return ExampleData.Players();
        }

        public void SubmitTurn(string choice)
        {
        }

        public ActionResult CheckTurn()
        {
            //Kalla på relevant serviceclient-metod som kontrollerar vems tur det är.
            //Data för användare samt spelsessions id finns sparat i sessionsvariablerna User samt GameSessionId

            GameInfo g = new GameInfo();
            g.TotalNumOfGameRounds = 2;
            g.WinningPlayerID = 4;

            PlayedGameRound p = new PlayedGameRound();
            p.GameRoundNumber = 1;
            p.WinningPlayerID = 2;
            p.PlayerChoices = new List<PlayerChoice>();

            PlayerChoice c = new PlayerChoice();
            c.Choice = 1;
            c.PlayerID = 1;

            p.PlayerChoices.Add(c);

            PlayedGameRound p1 = new PlayedGameRound();
            p1.GameRoundNumber = 1;
            p1.WinningPlayerID = 2;
            p1.PlayerChoices = new List<PlayerChoice>();

            PlayerChoice c1 = new PlayerChoice();
            c1.Choice = 1;
            c1.PlayerID = 1;

            p1.PlayerChoices.Add(c1);

            List<PlayedGameRound> l = new List<PlayedGameRound>();
            l.Add(p);
            l.Add(p1);

            g.PlayedGameRounds = l;

            return Json(g, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GoToStart()
        {
            GetActiveGames(Session["User"].ToString());
            return View("Start");
        }

        public ActionResult ShowGameSession()
        {
            //List<GameSession> exData = ExampleData.GameSessions();
            //int idToSearchFor;
            //Int32.TryParse(id, out idToSearchFor);

            //foreach (GameSession g in exData)
            //{
            //    if(g.ID == idToSearchFor) 
            //    {
                    //ViewBag.GameTitle = g.Game.Name;
                    //ViewBag.GameId = g.ID;
                    //ViewBag.NumOfRounds = g.NumberOfRounds;
            ViewBag.GameTitle = "RockPaperScissor";
                    ViewBag.GameId = 3;
                    ViewBag.NumOfRounds = 7;
                    ViewBag.Players = GetPlayers();
                    return View("RockPaperScissor");
            //    }
            //}
            //return View("Start");
        }

        /// <summary>
        /// Tar emot ett id (som representerar vilken spelsession spelaren ska joina)
        /// Lägger till spelaren, genom spelarens, id till spelsessionen i fråga
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult JoinGame(string id)
        {
            int userId;
            Int32.TryParse(Session["UserId"].ToString(), out userId);

            int sessionId;
            Int32.TryParse(id, out sessionId);

            var service = new AwesomeClient();
            service.AddPlayerSession(userId, sessionId);

            return GoToStart();
        }

        /// <summary>
        /// Frågar WCF:en om motståndarens status (om hen gjort ett val eller inte)
        /// </summary>
        /// <param name="playerId"></param>
        /// <param name="gameSessionId"></param>
        /// <returns></returns>
        public bool CheckOpponentStatus(string playerId, string gameSessionId)
        {
            
            return false;
        }

    }
}
